package com.dap.utils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class SpringDataRedisUtils implements InitializingBean {


    private static JedisConnectionFactory factory ;
    private static RedisTemplate redisTemplate ;
    JedisPoolConfig config;
    //最大连接数
    private String redis_max_active = "100";
    //最大空闲连接数
    private String redis_max_idle = "10";
    //获取连接时最大等待毫秒数,如果该值小于0,则阻塞不确定的时长,默认值-1
    private String redis_max_wait = "1500";
    //超时
    private String redis_timeout = "2000";
    @Value("${host}")
    private String host;
    @Value("${port}")
    private String port;

    public RedisTemplate getRedisTemplate() {

        redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        //为key设置序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //为value设置序列化器
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

        System.out.println(host+port);

        config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(redis_max_active));
        config.setMaxIdle(Integer.parseInt(redis_max_idle));
        config.setMaxWaitMillis(Integer.parseInt(redis_max_wait));
        // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的
        config.setTestOnBorrow(true);

        factory = new JedisConnectionFactory();
        //关联链接池的配置对象
        factory.setPoolConfig(config);
        //配置链接Redis的信息
        //主机地址

        factory.setHostName(host);
        //端口
        factory.setPort(Integer.parseInt(port));

    }


}
